package com.nineclock.auth.processor;

import cn.hutool.crypto.digest.BCrypt;
import com.nineclock.auth.entity.IntegrationAuthenticationEntity;
import com.nineclock.common.constant.SMSConstant;
import com.nineclock.common.enums.ResponseEnum;
import com.nineclock.common.exception.NcException;
import com.nineclock.system.dto.SysUserDTO;
import com.nineclock.system.feign.SysUserFeign;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Component;

/**
 * 验证码模式认证处理器
 */
//被spring容器识别
@Component
public class SmsAuthenticationProcessor implements AuthenticationProcessor {
    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @Autowired
    SysUserFeign userFeign;
    @Override
    public SysUserDTO authenticate(IntegrationAuthenticationEntity entity) {
        String mobile = entity.getAuthParameter("mobile");
        String code = entity.getAuthParameter("password");
        if (mobile == null || code == null){
            throw new NcException(ResponseEnum.INVALID_USERNAME_PASSWORD);
        }
        SysUserDTO userDTO = userFeign.queryUser(mobile).getData();
        if (userDTO == null){
            throw new NcException(ResponseEnum.USER_NOT_FOUND);
        }
        //从redis获取对应的验证码
        String key  = SMSConstant.SMS_LOGIN_KEY_PREFIX+mobile;
        redisTemplate.boundValueOps(key).get();
        //把验证码的 密文 存储到 userDTO中
        userDTO.setPassword(new BCryptPasswordEncoder().encode(code));
        return userDTO;
    }

    @Override
    public boolean support(IntegrationAuthenticationEntity entity) {
        if (entity != null && "sms".equalsIgnoreCase(entity.getAuthType())){
            return true;
        }
        return false;
    }
}
